package com.lp.serialportlibrary.thread;

import android.util.Log;


import java.io.IOException;
import java.io.InputStream;

/**
 * Created by lp on 2017/11/14.
 * 串口消息读取线程
 */

public abstract class SerialPortReadThread extends Thread {

    public abstract void onDataReceived(byte[] bytes);

    private static final String TAG = SerialPortReadThread.class.getSimpleName();
    private InputStream mInputStream;
    private byte[] mReadBuffer;

    public SerialPortReadThread(InputStream inputStream) {
        mInputStream = inputStream;
        mReadBuffer = new byte[1024];
    }

    @Override
    public void run() {
        super.run();
        try {
            while (!isInterrupted()) {
                try {
                    if (null == mInputStream) {
                        return;
                    }

                    int size = 0;
                    //先检查是否有可获取的数据，避免read一直阻塞无法释放
                    if (mInputStream.available() > 0) {
                        size = mInputStream.read(mReadBuffer);
                    }else {
//                        TimeUtil.delayMs(20);
                        continue;
                    }
                    if (size <= 0) {
                        Log.i(TAG, "size <=0: ");
                        return;
                    }

                    byte[] readBytes = new byte[size];

                    System.arraycopy(mReadBuffer, 0, readBytes, 0, size);
//
//                    Log.i(TAG, " readBytes = " + StringTool.byteHexToSting(readBytes));
//                    Log.i(TAG, " Thread.currentThread().id = " + Thread.currentThread().getId());
                    onDataReceived(readBytes);

                } catch (IOException e) {
                    e.printStackTrace();
                    return;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public synchronized void start() {
        super.start();
    }

    /**
     * 关闭线程 释放资源
     */
    public void release() {
        interrupt();
        if (null != mInputStream) {
            try {
                Log.i(TAG, "release: ");
                mInputStream.close();
                mInputStream = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
